package com.decent.common.util;


import cn.hutool.core.util.StrUtil;

import java.util.regex.Pattern;

/**
 * 规则验证
 *
 * @author 唐全成
 */
@SuppressWarnings({"unused", "BooleanMethodIsAlwaysInverted"})
public class PatternCheckUtils {

    /**
     * 只匹配汉字
     */
    private static final String CHINESE_CHARACTER = "^[\\u4e00-\\u9fa5]{0,}$";

    /**
     * 自定义校验规则
     *
     * @param regx  正则表达式
     * @param value 待校验的值
     */
    public static boolean customCheck(String regx, String value) {
        if (StrUtil.isBlank(regx)) {
            return false;
        }
        Pattern compile = Pattern.compile(regx);
        return StrUtil.isNotBlank(value) && compile.matcher(value).matches();
    }

    /**
     * 校验是否是中文
     *
     * @param value 校验值
     * @return 结果
     */
    public static boolean checkChinese(String value) {
        return customCheck(CHINESE_CHARACTER, value);
    }

    /**
     * 校验是否有中文及中文符号
     *
     * @param value 校验值
     * @return 结果
     */
    public static boolean checkChineseCharacter(String value) {
        char[] ch = value.toCharArray();
        for (char c : ch) {
            if (isChinese(c)) {
                return true;
            }

        }
        return false;
    }

    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                // GENERAL_PUNCTUATION 判断中文的“号
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                // CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                // HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的，号
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
    }
}
